<template>
  <div class="certificate">
    <jc-button
      :btn-arr="['pass', 'copy', 'save', 'reload', 'sub', 'remove', 'cashFlow', 'list']"
      :list="'/certificate'"
      @refresh="certificate"
      @save="save"
      @audit="audit(1)"
      @noAudit="audit(2)"
      @submit="save(1)"
      @noSubmit="submit(2)"
      @del="delCertif"
      @copyDa="copyDa"
      @cashFlow="designVis=true"
    />
    <el-tabs v-model="activeName">
      <el-tab-pane :label="$t('menu.certificateDetail')" name="first">
        <el-form :model="prodValue" size="mini" label-width="120px">
          <el-form-item :label="$t('market.documentstatus')">
            <el-tag :type="prodValue.stateColor">{{ prodValue.fdocumentstatus }}</el-tag>
          </el-form-item>
          <el-form-item :label="$t('market.voucherNum')">
            <el-input v-model="prodValue.fbillNo" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.voucherdate')">
            <el-date-picker
              v-model.trim="prodValue.voucherdate"
              type="date"
              value-format="yyyy-MM-dd"
              :disabled="isdisable"
              @change="handelDate"
            />
          </el-form-item>
          <el-form-item :label="$t('market.frombillNo')">
            <el-input v-model="prodValue.frombillNo" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.frombillNoType')">
            <el-input v-model="prodValue.fbillNo" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.vwordId')">
            <el-select v-model="prodValue.vwordId" :disabled="isdisable">
              <el-option
                v-for="item in vwordData"
                :key="item.fvalue"
                :label="item.fname"
                :value="item.fid"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('market.vNumber')">
            <el-input v-model="prodValue.vNumber" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.note')">
            <el-input v-model="prodValue.remark" :disabled="isdisable" />
          </el-form-item>
          <el-form-item>
            <span v-if="prodValue.fcashappoint === 'Y'" style="color: red">已指定现金流</span>
          </el-form-item>
        </el-form>
        <div>
          <div style="margin-bottom: 5px;">
            <el-button size="mini" @click="newly(1)">{{ $t('btn.newHang') }}<!--新增行--></el-button>
            <el-button size="mini" @click="newly(3)">{{ $t('btn.insertHang') }}<!--插入行--></el-button>
            <el-button size="mini" @click="newly(2)">{{ $t('btn.delHang') }}<!--删除行--></el-button>
          </div>
          <jc-table
            :table-data="tableData"
            :table-header="tableHearder"
            serial
            :get-summaries="getSummaries"
            show-summary
            :table-height="tableHeight"
            @rowClick="rowClick"
          >
            <!-- 摘要 -->
            <template v-slot:tagSlot="col">
              <el-input v-model="col.scope.row.description" size="mini" :disabled="isdisable" />
            </template>
            <!-- 核算维度 -->
            <template v-slot:orderSlot="col">
              <el-input v-model="col.scope.row.dimensionString" size="mini" :disabled="isdisable">
                <i
                  slot="suffix"
                  class="el-input__icon el-icon-search"
                  @click="dimenOpen(col.scope.$index)"
                />
              </el-input>
            </template>
            <!-- 借方金额 -->
            <template v-slot:billSlot="col">
              <el-input-number v-model="col.scope.row.amountIn" size="mini" :disabled="isdisable" @change="anountHandel(col.scope.$index)" />
            </template>
            <!-- 贷方金额 -->
            <template v-slot:btnState="col">
              <el-input-number v-model="col.scope.row.amountOut" size="mini" :disabled="isdisable" @change="anountHandel1(col.scope.$index)" />
            </template>
            <!-- 原币金额 -->
            <template v-slot:text3Slot="col">
              <el-input-number v-model="col.scope.row.foriamount" size="mini" :disabled="isdisable" @change="anountHandel2(col.scope.$index)" />
            </template>
            <!-- 科目名称 -->
            <template v-slot:btnStates="col">
              <el-input v-model="col.scope.row.subjectName" size="mini" :disabled="isdisable">
                <i
                  slot="suffix"
                  class="el-input__icon el-icon-search"
                  @click="sujectOpen(col.scope.$index)"
                />
              </el-input>
            </template>
            <!--币别-->
            <template v-slot:text2Slot="col">
              <el-input v-model="col.scope.row.fsettlecurr" size="mini" :disabled="isdisable">
                <i
                  slot="suffix"
                  class="el-input__icon el-icon-search"
                  @click="currOpen(col.scope.$index)"
                />
              </el-input>
            </template>
            <!--汇率-->
            <template v-slot:text1Slot="col">
              <el-input-number
                v-model="col.scope.row.exchangerate"
                size="mini"
                :disabled="isdisable"
                @change="handelChange(col.scope.$index)"
              />
            </template>
          </jc-table>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('market.other')" name="log">
        <jc-form
          :options="other"
          :option-value="otherUrlObject"
          label-width="100px"
        />
      </el-tab-pane>
    </el-tabs>
    <!--    科目列表-->
    <subjectList v-if="isSubListVisibled" @subject="sublistData" />
    <!-- 维度 -->
    <dimenDialog v-if="isDimenDataVisibled" :dimen-list="dimenList" @subject="dimenData" />
    <!--结算币别列表-->
    <currency v-if="currencyVisiblit" @currency="currencyData" />
    <!--  现金流量项目指定  -->
    <designProject v-if="designVis" :fid="prodValue.voucherId" @currency="designVis=false" />
  </div>
</template>

<script>
import jcForm from '@/components/Form'
import { toMxBmina } from '@/components/ToMxamineState'
import {
  queryVoucherDetail, updateVouchers,
  unauditVouchers, auditVouchers,
  notsubmitVouchers, submitVouchers,
  delVouchers, queryCurrencyDtl
} from '@/api/financial/voucher'
import jcButton from '@/components/Button'
import subjectList from '@/views/financial/voucherTemplate/components/subjectList'
import dimenDialog from '@/views/financial/voucherTemplate/certificateAdd/component/dimenDialog'
import { querySubjectDetailsByfrealId } from '@/api/financial/subject'
import { queryViewItem } from '@/api/marketManage/marketOrder'
import jumpMateriel from '@/components/JumpMateriel'

export default {
  components: {
    designProject: () => import('@/views/financial/voucherTemplate/certificateDetail/components/designProject'),
    currency: () => import('@/views/market/marketManage/createMarkerOrder/components/currency'),
    jcForm,
    jcButton,
    subjectList,
    dimenDialog
  },
  mixins: [jumpMateriel],
  data() {
    return {
      activeName: 'first',
      designVis: false, // 现金流量
      isSubListVisibled: false, // 科目列表
      isDimenDataVisibled: false, // 维度列表
      currencyVisiblit: false, // 币别
      dimenList: [],
      vwordData: [],
      options: {},
      other: {
        createor: { label: this.$t('market.creator'), span: 6, disabled: 'disabled' },
        createdate: { label: this.$t('market.createDate'), span: 6, disabled: 'disabled' },
        approver: { label: this.$t('market.approver'), span: 6, disabled: 'disabled' },
        approverdate: { label: this.$t('market.approveDate'), span: 6, disabled: 'disabled' },
        modifier: { label: this.$t('market.modifier'), span: 6, disabled: 'disabled' },
        modifydate: { label: this.$t('market.modifyDate'), span: 6, disabled: 'disabled' },
        closer: { label: this.$t('market.closeor'), span: 6, disabled: 'disabled' },
        closedate: { label: this.$t('market.closeyDate'), span: 6, disabled: 'disabled' }
      },
      tableHeight: '70vh',
      otherUrlObject: {},
      prodValue: {},
      tableData: [],
      tableHearder: [
        { label: this.$t('market.digest'), type: 'tag', prop: 'description', width: '200' },
        { label: this.$t('market.subjectNum'), prop: 'subjectNumber', width: '100' },
        { label: this.$t('market.subjectName'), type: 'states', prop: 'subjectName', width: '150' },
        { label: this.$t('market.dimensionString'), type: 'order', prop: 'dimensionString', width: '200' },
        { label: this.$t('market.currency2'), type: 'text2', prop: 'fsettlecurr', width: '150' },
        { label: this.$t('market.exchangeType'), prop: 'fexchangetype', width: '120' },
        { label: this.$t('market.exchangeRate'), type: 'text1', prop: 'exchangerate', width: '120' },
        { label: this.$t('market.currAmount'), type: 'text3', prop: 'foriamount', width: '120' },
        { label: this.$t('market.amountIn'), type: 'bill', prop: 'amountIn', width: '100' },
        { label: this.$t('market.amountOut'), type: 'state', prop: 'amountOut', width: '100' }
      ],
      delArr: [],
      indexSelf: 0,
      isdisable: false
    }
  },
  created() {
    this.certificate()
    this.queryWord()
  },
  methods: {
    // 凭证字
    async queryWord() {
      const { data: RES } = await queryViewItem({ viewName: 'SX_VOUCHER_WORD' })
      this.vwordData = RES.list
    },
    // 修改
    save(ev) {
      this.prodValue.detail = this.tableData
      this.prodValue.delArr = this.delArr
      const DATA = {
        ...this.prodValue
      }
      updateVouchers(DATA).then(res => {
        if (res.code === 0) {
          ev === 1 ? this.submit(1) : this.certificate()
          this.delArr = []
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 详情
    certificate() {
      const id = this.$route.params.id
      if (!id) return
      queryVoucherDetail({ voucherId: id }).then(res => {
        if (res.code === 0) {
          this.prodValue = toMxBmina(res.data)
          this.isdisable = this.prodValue.fdocumentstatus === this.$t('market.state1') || this.prodValue.fdocumentstatus === this.$t('market.state2')
          this.otherUrlObject = res.data
          this.tableData = res.data.detail
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 科目列表
    sujectOpen(index) {
      this.indexSelf = index
      this.isSubListVisibled = true
    },
    // 科目数据
    sublistData(item) {
      if (item.fsubjectId) {
        const ite = this.tableData[this.indexSelf]
        ite.subjectId = item.fsubjectId
        ite.subjectName = item.fname
        ite.subjectNumber = item.fnumber
        this.courseData(ite.subjectId, ite.dimensionList?.[0]?.frealId || 0)
      }
      this.isSubListVisibled = false
    },
    // 获取科目维度
    courseData(fid, frealId) {
      querySubjectDetailsByfrealId({ fid, frealId }).then(res => {
        const ite = this.tableData[this.indexSelf]
        ite.dimensionString = ''
        ite.dimensionList = res.data.dismensionList
        ite.fexchangetypeid = res.data.fexchangetypeid
        ite.fexchangetype = res.data.fexchangetype
        ite.exchangerate = res.data.exchangerate
        ite.fsettlecurr = res.data.fsettlecurr
        ite.fsettlecurrid = res.data.fsettlecurrid
        res.data.dismensionList?.forEach(res => {
          if (res.frealNumber) ite.dimensionString += res.frealNumber + '/' + res.frealName + ';'
        })
      })
    },
    // 维度
    dimenOpen(index) {
      this.isDimenDataVisibled = true
      this.indexSelf = index
      this.dimenList = this.tableData[this.indexSelf].dimensionList
    },
    dimenData(ev, en) {
      if (ev?.length > 0 && ev[0].frealNumber) {
        this.tableData[this.indexSelf].dimensionList = ev || []
        this.tableData[this.indexSelf].dimensionString = en
      }
      this.isDimenDataVisibled = false
    },
    // 原币金额
    anountHandel(index) {
      const item = this.tableData[index]
      if (item.amountIn > 0) {
        item.amountOut = 0
      }
      item.foriamount = ((item.amountIn + item.amountOut) / item.exchangerate).toFixed(2)
    },
    anountHandel1(index) {
      const item = this.tableData[index]
      if (item.amountOut > 0) {
        item.amountIn = 0
      }
      item.foriamount = ((item.amountIn + item.amountOut) / item.exchangerate).toFixed(2)
    },
    anountHandel2(index) {
      const item = this.tableData[index]
      if (item.amountIn > 0) item.amountIn = (item.foriamount * item.exchangerate).toFixed(2)
      if (item.amountOut > 0) item.amountOut = (item.foriamount * item.exchangerate).toFixed(2)
    },
    handelChange(index) {
      const item = this.tableData[index]
      item.foriamount = ((item.amountIn + item.amountOut) / item.exchangerate).toFixed(2)
      if (item.amountIn > 0) item.amountIn = (item.foriamount * item.exchangerate).toFixed(2)
      if (item.amountOut > 0) item.amountOut = (item.foriamount * item.exchangerate).toFixed(2)
    },
    // 币别
    currOpen(index) {
      this.indexSelf = index
      this.currencyVisiblit = true
    },
    // 获取结算币别数据(子传父)
    currencyData(item) {
      if (item.fsettleCurrId) {
        const ite = this.tableData[this.indexSelf]
        ite.fsettlecurr = item.fsettleCurrIdName
        ite.fsettlecurrid = item.fsettleCurrId
        this.queryCurrency(item.fsettleCurrId)
      }
      this.currencyVisiblit = false
    },
    // 选中币别获取汇率 类型
    queryCurrency(fsettlecurrid) {
      const ite = this.tableData[this.indexSelf]
      queryCurrencyDtl({ fsettlecurrid, fdate: this.prodValue.voucherdate }).then(res => {
        if (res.code === 0) {
          ite.fsettlecurr = res.data.fsettlecurr
          ite.fsettlecurrid = res.data.fsettlecurrid
          ite.fexchangetypeid = res.data.fexchangetypeid
          ite.fexchangetype = res.data.fexchangetype
          ite.exchangerate = res.data.exchangerate
          this.handelChange(this.indexSelf)
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 凭证日期
    handelDate() {
      this.tableData.forEach((res, index) => {
        this.indexSelf = index
        this.queryCurrency(res.fsettlecurrid)
        setTimeout(() => {
          this.anountHandel2(index)
        }, 500)
      })
    },
    // 复制
    copyDa() {
      this.$router.push({
        path: '/certificateAdd',
        query: {
          id: this.prodValue.voucherId
        }
      })
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 新增删除行
    newly(ev) {
      const DATA = {
        fexchangetype: '',
        exchangerate: 0,
        fsettlecurr: '',
        description: '',
        amountIn: '',
        amountOut: '',
        subjectName: '',
        subjectNumber: ''
      }
      if (ev === 1) {
        this.tableData.push(DATA)
      } else if (ev === 2) { // 删除
        const item = this.tableData[this.indexSelf].voucherdetailId
        this.delArr.push(item)
        this.tableData.splice(this.indexSelf, 1)
      } else if (ev === 3) { // 插入
        this.tableData.splice(this.indexSelf + 1, 0, DATA)
      }
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: [this.prodValue.fbillNo] }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
        this.certificate()
      })
    },
    // 审批通过
    async audit(ev) {
      const api = ev === 1 ? auditVouchers : unauditVouchers
      this.toExamineFun(api)
    },
    // 提交反提交
    async submit(ev) {
      const api = ev === 1 ? submitVouchers : notsubmitVouchers
      this.toExamineFun(api)
    },
    // 删除
    delCertif() {
      this.$confirm('该操作将永久删除凭证，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        const DATA = { Numbers: [this.prodValue.fbillNo] }
        delVouchers(DATA).then(res => {
          if (res.code === 0) {
            // 关闭当前页面
            this.$store.dispatch('tagsView/guanbi', this.$route)
            this.$router.push({ path: '/certificate' })
            this.$message({ showClose: true, message: res.message, type: 'success' })
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.certificate {
  @include listBom;
  min-height: 89vh;
  .el-input::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
  .el-form {
    display: flex;
    flex-wrap: wrap;

    .el-form-item {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      height: 35px;
      width: 290px;
      margin-bottom: 5px;

      .el-date-editor.el-input {
        width: 100% !important;
      }

      .el-select {
        width: 100%;
      }
    }
  }
}
</style>
